package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sosee.cgfw.R;
import com.sosee.cgfw.entity.AvatarToJson;
import com.sosee.cgfw.entity.User;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import droid.Activity01;

/**
 * Created by Thinkpad on 2016/3/2.
 */
public class PersonalInfo extends Activity {
    private TextView tv_nickname;
    private TextView tv_name;
    private TextView tv_gender;
    private TextView tv_company;
    private TextView tv_qita;
    private TextView tv_born;
    private String context;//向修改页面传递的内容
    private int from;//标注修改信息
    private TextView tv_myName;
    private HttpUtils httpUtils;
    private ImageView ig_avatar;//用户头像
    private BitmapUtils bitmapUtils;
    private TextView tv_loc;//用户所在地

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        initView();
        initData();
    }
    //返回键
    public void onClick(View view){
        finish();
    }



    public void initView(){
        ig_avatar= (ImageView) findViewById(R.id.ig_avatar);
        httpUtils=new HttpUtils();
        tv_myName= (TextView) findViewById(R.id.tv_myName);
        tv_nickname= (TextView) findViewById(R.id.tv_nickname);
        tv_name= (TextView) findViewById(R.id.tv_name);
        tv_gender= (TextView) findViewById(R.id.tv_gender);
        tv_company= (TextView) findViewById(R.id.tv_company);
        tv_qita= (TextView) findViewById(R.id.tv_qita);
        tv_born= (TextView) findViewById(R.id.tv_born);
        tv_loc= (TextView) findViewById(R.id.tv_loc_w);
    }


    public void initData(){
        bitmapUtils=new BitmapUtils(this);
        context=getIntent().getStringExtra("context");
        from=getIntent().getIntExtra("key",-1);
        switch (from){
            case 0:
                Constans.user.setNickname(context);
                break;
            case 1:
                Constans.user.setRealname(context);
                break;
            case 2:
                Constans.user.setSex(context);
                break;
            case 3:
                Constans.user.setBirth(context);
                break;
            case 4:
                Constans.user.setCompany(context);
                break;
            case 5:
                Constans.user.setDuty(context);
                break;
            case 7:
                Constans.user.setLocation(context);
                break;
        }
        User user= Constans.user;
        tv_nickname.setText(user.getNickname());
        tv_name.setText(user.getRealname());
        tv_company.setText(user.getCompany());
        tv_gender.setText(user.getSex());
        tv_born.setText(user.getBirth());
        tv_qita.setText(user.getDuty());
        tv_myName.setText(user.getNickname());
        tv_loc.setText(user.getLocation());
        //显示用户头像
        String pic=Constans.user.getPic();

        if(user.getBit()!=null){
            ig_avatar.setImageBitmap(user.getBit());
        }else{
            if(pic!=null&&pic.length()>2){
                URL url=null;
                try {
                     url=new URL(Constans.BASE_URL+pic);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                Utils.onLoadImage(url, new Utils.OnLoadImageListener() {
                    @Override
                    public void OnLoadImage(Bitmap bitmap, String bitmapPath) {
                        ig_avatar.setImageBitmap(bitmap);
                        Constans.user.setBit(bitmap);
                    }
                });
            }
        }




    }

    //修改用户信息点击事件
    public void click(View view){
        Intent intent=new Intent(this,UpdatePersonalInfoActivity.class);;
        int id=view.getId();
        switch (id){
            //昵称
            case R.id.rl_nick:
                from=0;
                context=tv_nickname.getText().toString().trim();

                break;
            //姓名
            case R.id.rl_name:
                from=1;
                context=tv_name.getText().toString().trim();

                break;
            //单位
            case R.id.rl_com:
                from=4;
                context=tv_company.getText().toString().trim();

                break;
            //出生日期
            case R.id.rl_born:
                from=3;
                context=tv_born.getText().toString().trim();
                break;
            //性别
            case R.id.rl_gender:
                from=2;
                context=tv_gender.getText().toString().trim();
                break;
            //身份
            case R.id.rl_qita:
                from=5;
                context=tv_qita.getText().toString().trim();
                break;
            case R.id.rl_loc:
                intent=new Intent(this, Activity01.class);
                break;
        }
        intent.putExtra("key", from);
        intent.putExtra("context", context);
        startActivity(intent);
        finish();

    }

    public void avatar(View view){
        getPic();
    }



    //打开系统相册  "image/*"
    //外网暂时未开放此功能
    private int RESULT_LOAD_IMAGE=0;
    public void getPic(){
        Intent intent = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);

    }
    private String imgUrl;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            LogUtils.log_E("图片路劲：==" + picturePath);


//            Bitmap bit= BitmapFactory.decodeFile(picturePath);
            imgUrl=picturePath;
//            updateAvatar();
//            bit=small(bit);
//            imageView.setImageDrawable(resizeImage(bit, imageView.getWidth(), imageView.getHeight()));

            //获取指定图片的缩略图
            Bitmap bit=getImageThumbnail(picturePath, 60, 60);
            ig_avatar.setImageBitmap(bit);
            Constans.user.setBit(bit);

            try {
                saveBitmap(bit);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 根据指定的图像路径和大小来获取缩略图
     * 此方法有两点好处：
     *     1. 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     *        第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。
     *     2. 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使
     *        用这个工具生成的图像不会被拉伸。
     * @param imagePath 图像的路径
     * @param width 指定输出图像的宽度
     * @param height 指定输出图像的高度
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }
    private String path=Constans.PIC_SHARE+"ava.jpg";



    private void saveBitmap(Bitmap bitmap) throws IOException
    {
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        FileOutputStream out;
        try{
            out = new FileOutputStream(file);
            if(bitmap.compress(Bitmap.CompressFormat.PNG, 90, out))
            {
                out.flush();
                out.close();
                updateAvatar(bitmap);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    //修改用户头像
    private Bitmap bit;
    public void updateAvatar(Bitmap bit){
        AvatarToJson json=new AvatarToJson();
        json.setUserid(Constans.userID);
        json.setPic(Utils.imgToBase64(path, bit, ""));
        int index=imgUrl.indexOf(".");
        String type=imgUrl.substring(index+1);
        LogUtils.log_E("测试type："+type);
        json.setType(type);

        RequestParams params=new RequestParams();
        String jso=com.alibaba.fastjson.JSONObject.toJSONString(json);
        try {
            params.setContentType("application/json");
            params.setBodyEntity(new StringEntity(jso,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, Constans.AVATAR_URL,params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtils.log_E("测试上传头像"+responseInfo.result);
                try {
                    JSONObject jsonObject=new JSONObject(responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){
                        String url=jsonObject.getString("msg");
                        Constans.user.setPic(url);//保存用户修改后的头像地址
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常");

            }
        });

    }



    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }







    //压缩图片
    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
        return resizeBmp;
    }
    //指定大小对图片进行压缩

    public static Drawable resizeImage(Bitmap bitmap, int w, int h)
    {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        float n=scaleHeight>scaleWidth?scaleHeight:scaleWidth;

        Matrix matrix = new Matrix();
        matrix.postScale(n, n);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return new BitmapDrawable(resizedBitmap);
    }



}
